<template>
	<div class="wallet-withdraw flex flex-col flex-1">
		<wallet-deposit-types
			ref="walletWithdrawTypeRef"
			:data-list="commonPaymentMethods"
			@select="selectType" />
		<div class="mt-2 px-[35px] pb-6 flex flex-col flex-1">
			<template v-if="bankType.includes(Number(selectedMethodType))">
				<p class="pt-[6px] pb-[10px]">{{ $t('validate.cardNumber') }}</p>
				<wallet-select-bank
					class="min-h-[200px]"
					:options="list"
					v-model:modelValue="bankValue"
					@add="handleAddItem(WalletType.bank.id)"
					@delete="onDeleteBank"
					@unableTrigger="onTrigger"
					:disabled="!withdrawAble" />
			</template>

			<template v-else>
				<p class="pt-[6px] pb-[10px]">{{ $t('WalletType.usdt') }}</p>

				<wallet-select-bank
					class="min-h-[200px]"
					:options="addressesList"
					v-model:modelValue="addressValue"
					@add="handleAddItem(WalletType.usdt.id)"
					@delete="onDeleteUSDT"
					@unableTrigger="onTrigger"
					:disabled="!withdrawAble" />
			</template>

			<div class="mt-[50px] p-[11px] rounded-[5px] bg-bg-3 text-sm" v-if="allTaskNum > 0">
				<p class="text-success" v-if="withdrawAble">
					<base-icon name="correct2" class="text-success" />
					{{ t('wallet.completedTip') }}
				</p>
				<template v-else>
					<div class="text error">
						<base-icon name="remove" />
						{{ t('wallet.unCompleteTip') }}
					</div>
					<p class="need-complete app-font-bold">
						{{
							t('wallet.needCompleteTip', {
								amount:
									currency + ' ' + fmtAmount(unCompleteTaskAmount, { hideCurrenySymbol: true })
							})
						}}
					</p>
				</template>
				<p class="text-t-2">{{ t('wallet.withdrawAbleTip') }}</p>
			</div>
			<div class="flex-1"></div>

			<base-button
				type="primary"
				:disabled="disableButtonNext"
				@click="onSubmit"
				class="mt-10 mb-[20px] w-full mx-auto">
				{{ $t('wallet.nextStep') }}
			</base-button>
		</div>

		<wallet-complete-dialog v-model="showDialog" />
		<withdraw-bank />
		<bank-card-add />
		<usdt-address-add />
	</div>
</template>

<script lang="ts" setup>
import { computed, nextTick, onMounted, ref, watch } from 'vue'
import { bankType, WalletType } from '@/enums'
import { useAppStore, useWalletStore } from '@/store'
import { fmtAmount, fmtMobile, showError, showSuccess, t } from '@/utils'
import { removeCard, removeCryptoAddress } from '@/api/wallet.ts'
import { useDialog } from '@/hooks/useDialog.ts'
import { BaseButton, BaseIcon } from '@/components/base'
import WithdrawBank from '@/views/wallet/withdraw/index.vue'
import WalletDepositTypes from '@/views/wallet/wallet/wallet-deposit-types.vue'
import WalletSelectBank from '@/views/wallet/components/wallet-select-bank.vue'
import BankCardAdd from '@/views/wallet/bank-card-add/index.vue'
import WalletCompleteDialog from '@/views/wallet/components/wallet-complete-dialog.vue'
import UsdtAddressAdd from '@/views/wallet/usdt-address-add/index.vue'

const BANK_LIST = [
	{
		id: WalletType.bank.id,
		icon: `wallet-type/${WalletType.bank.id}.png`,
		paymentMethodCode: 'Bank',
		paymentMethod: 'Bank Transfer',
		text: 'wallet.cardBank'
	},
	{
		id: WalletType.alipay.id,
		icon: `wallet-type/${WalletType.bank.id}.png`,
		paymentMethodCode: 'Bank',
		paymentMethod: 'Bank Transfer',
		text: 'wallet.cardBank'
	},
	{
		id: WalletType.weixin.id,
		icon: `wallet-type/${WalletType.bank.id}.png`,
		paymentMethodCode: 'Bank',
		paymentMethod: 'Bank Transfer',
		text: 'wallet.cardBank'
	},
	{
		id: WalletType.paypal.id,
		icon: `wallet-type/${WalletType.bank.id}.png`,
		paymentMethodCode: 'Bank',
		paymentMethod: 'Bank Transfer',
		text: 'wallet.cardBank'
	},
	{
		id: WalletType.usdt.id,
		icon: `wallet-type/${WalletType.usdt.id}.png`,
		paymentMethodCode: 'crypto',
		paymentMethod: 'USDT',
		text: 'wallet.usdt'
	}
]

const walletStore = useWalletStore()
const commonPaymentMethods = computed(() => {
	const bankItemWithBankCode = BANK_LIST.filter((bankItem) =>
		walletStore.channelInfo.channelList.some(
			(bItem: any) => bItem.seq === bankItem.id && bankItem.paymentMethodCode === 'Bank'
		)
	)
	const filteredBankList = BANK_LIST.filter((bankItem) => bankItem.paymentMethodCode !== 'Bank')
	if (bankItemWithBankCode.length > 1) {
		return [bankItemWithBankCode[0], ...filteredBankList]
	}
	return [...bankItemWithBankCode, ...filteredBankList]
})

const appStore = useAppStore()
const bankValue = ref('')
const addressValue = ref('')
const withdrawAble = computed(() => walletStore.withdrawChannel.withdrawAble)
const allTaskNum = computed(() => walletStore.withdrawChannel.allTaskNum)
const currency = computed(() => appStore.currency)
const unCompleteTaskAmount = computed(() => walletStore.withdrawChannel.unCompleteTaskAmount)
// const addressSelectShow = ref(false)
const selectedMethodType = ref()
const showDialog = ref(false)
const { warning } = useDialog()

const list: any = computed({
	get: () => {
		const data: any = {
			id: 'add',
			textDisplay: t('wallet.bankCardSelect'),
			text: t('wallet.bankCardAdd'),
			img: 'wallet-type/3.png',
			type: ''
		}
		const ls = walletStore.cards.map((item: any) => ({
			id: item.id,
			text: item.bankName,
			content: fmtMobile(item.cardNumber),
			img: item.bankIcon,
			type: 'server'
		}))
		ls.unshift(data)
		return ls
	},
	set: (newValue) => (list.value = newValue)
})

const addressesList = computed({
	get: () => {
		const data = {
			id: 'add',
			textDisplay: t('wallet.usdtAddressSelect'),
			text: t('wallet.usdtAddressAdd'),
			img: 'wallet-type/5.png',
			type: ''
		}
		const ls = walletStore.addresses.map((item: any) => ({
			id: item.id,
			text: String(item.crypto).toUpperCase(),
			content: item.address,
			img: `wallet-type/${WalletType.usdt.id}.png`
		}))
		ls.unshift(data)
		return ls
	},
	set: (newValue) => (list.value = newValue)
})

const walletWithdrawTypeRef: any = ref(null)
const disableButtonNext = computed(
	() =>
		(bankType.includes(selectedMethodType.value) && !bankValue.value) ||
		(selectedMethodType.value === WalletType.usdt.id && !addressValue.value)
)

const handleAddItem = (type: number) => {
	if (bankType.includes(type)) {
		walletStore.setWalletBankCardSelectPopupShow(true)
	} else {
		walletStore.setWalletUsdtAddressSelectPopupShow(true)

		// addressSelectShow.value = true
	}
}

const selectType = (data: any) => {
	selectedMethodType.value = data.id
}

const onSubmit = () => {
	walletStore.setWithdrawData({
		type: selectedMethodType.value,
		id: bankValue.value,
		usdtId: addressValue.value
	})
	walletStore.setWithdrawPopupShow(true)
}

const onDeleteBank = (id: any) => {
	if (Number(list.value.length) === 1) {
		// showFailToast({
		// 	message: t('httpCode[150]')
		// })
		return false
	}
	warning({
		content: t('wallet.deleteConfirmContent'),
		confirmFn: async () => {
			try {
				await removeCard({ id })
				showSuccess(t('wallet.bankCardRemoveSuccess'))
				list.value.splice(list.value.indexOf(list.value.filter((obj: any) => obj.id === id)))
				await walletStore.getAllCards()
			} catch (error: any) {
				showError(error)
			}
		}
	})
}

const onDeleteUSDT = (id: any) => {
	if (Number(addressesList.value.length) === 1) {
		return false
	}
	warning({
		content: t('wallet.deleteConfirmContent'),
		confirmFn: async () => {
			try {
				await removeCryptoAddress({ id })
				showSuccess(t('wallet.usdtAddressRemoveSuccess'))
				addressesList.value.splice(
					list.value.indexOf(addressesList.value.filter((obj: any) => obj.id === id))
				)
				await walletStore.getCryptoAddresses()
			} catch (error: any) {
				showError(error)
			}
		}
	})
}

const onTrigger = () => {
	showDialog.value = true
}

onMounted(() => {
	nextTick(() => {
		// walletWithdrawTypeRef.value.selectRechargeType(BANK_LIST[0], 0)
	})
	walletStore.getWithdrawChannel()
	walletStore.getCryptoAddresses()
	walletStore.getAllCards()
})

watch(
	() => commonPaymentMethods,
	(newValue) => {
		selectedMethodType.value = newValue.value?.[0]?.id
	},
	{
		immediate: true
	}
)
</script>
<style lang="scss" scoped></style>
